/**
 * Created with hong.rong
 * Date:2020/07/17
 */

import React, { useState, useEffect } from 'react'
import moment from 'moment'
import { Button, Upload } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import Oss from 'ali-oss'
import useUploadConfig from '@/hooks/useUploadConfig'

function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

const client = (config = {}) => {
  console.log(config)
  // 当时使用的插件版本为5.2
  /*
  return new oss.Wrapper({
    accessKeyId: token.access_key_id,
    accessKeySecret: token.access_key_secret,
    region: '', //
    bucket: '',//
  });
  */
  // 2018-12-29更新
  // ali-oss v6.x版本的写法
  return new Oss({
    accessKeyId: config.accessKey,
    accessKeySecret: config.accessSecret,
    stsToken: config.token,
    region: '', //
    bucket: '', //
    endpoint: '',
  })
}

const uploadPath = file => {
  console.log(file, 'uploadPath file')
  // 上传文件的路径，使用日期命名文件目录
  return `${moment().format('YYYYMMDD')}/${file.name.split('.')[0]}-${
    file.uid
  }.${file.type.split('/')[1]}`
}

const UploadToOss = (config, path, file) => {
  // const url = uploadPath(path, file)
  return new Promise((resolve, reject) => {
    client(config)
      .multipartUpload(path, file)
      .then(data => {
        resolve(data)
      })
      .catch(error => {
        reject(error)
      })
  })
}

export default function QrCode() {
  const { config } = useUploadConfig()

  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState('')

  const handleBeforeUpload = file => {
    const isJPG = file.type === 'image/jpeg'
    if (!isJPG) {
      message.error('You can only upload JPG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    let reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onloadend = () => {
      // 使用ossupload覆盖默认的上传方法
      const path = uploadPath(file)
      UploadToOss(config, path, file).then(data => {
        const res = data.res || {}
        setImageUrl(res.requestUrls)
      })
    }
    return false // 不调用默认的上传方法
  }

  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
        setImageUrl(imageUrl)
        setLoading(loading)
      })
    }
  }

  return (
    <Upload
      name="file"
      beforeUpload={handleBeforeUpload}
      onChange={handleChange}
    >
      <Button loading={loading}>
        <UploadOutlined /> 点击上传
      </Button>
    </Upload>
  )
}
